package com.ling.luo.base.producer;


import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 发送异步消息
 *
 * @author luohoujian
 * @since 2021/05/29
 */
public class AsyncProducer {

    /**
     * 消息发送者步骤分析
     * 1.创建消息生产者producer，并制定生产者组名
     * 2.指定Nameserver地址
     * 3.启动producer
     * 4.创建消息对象，指定主题Topic，Tag和消息体
     * 5.发送消息
     * 6.关闭生产者producer
     *
     * 备注：
     * Rocket MQ服务器 C:\Users\luohoujian01\softwareInstall\rocketmq-all-4.2.0-bin-release
     * 使用maven版本（rocketmq client）4.4.0 发送不了异步消息，报错
     * 使用（rocketmq client）3.5.8可以发送成功
     */
    public static void main1(String[] args) throws Exception {
        // * 1.创建消息生产者producer，并制定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        // * 2.指定Nameserver地址，多个使用;隔开 127.0.0.1:9876;127.0.0.1:9877
        producer.setNamesrvAddr("127.0.0.1:9876");
        // * 3.启动producer
        producer.start();
        producer.setRetryTimesWhenSendAsyncFailed(0);

        // * 4.创建消息对象，指定主题Topic，Tag和消息体
//        Message msg = new Message("topic1", "tag2", "hello rocketmq".getBytes());
        Message msg = new Message("Jodie_topic_1023",
                "TagA",
                //"OrderID188",
                "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
        // * 5.发送异步消息
        producer.send(msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功");
            }

            @Override
            public void onException(Throwable e) {
                System.out.println("发送异常" + e);
            }
        });
        System.out.println("异步消息发送完成");
        // * 6.关闭生产者producer
        producer.shutdown();
    }


    public static void main(String[] args) throws Exception {
        //Instantiate with a producer group name.
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        // Specify name server addresses.
        producer.setNamesrvAddr("localhost:9876");
        //Launch the instance.
        producer.start();
        producer.setRetryTimesWhenSendAsyncFailed(0);
        producer.setSendMsgTimeout(30000);

        int messageCount = 100;
        final CountDownLatch countDownLatch = new CountDownLatch(messageCount);
        for (int i = 0; i < messageCount; i++) {
            try {
                final int index = i;
                Message msg = new Message("Jodie_topic_1023",
                        "TagA",
                        "OrderID188",
                        "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                producer.send(msg, new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        countDownLatch.countDown();
                        System.out.printf("%-10d OK %s %n", index, sendResult.getMsgId());
                    }

                    @Override
                    public void onException(Throwable e) {
                        countDownLatch.countDown();
                        System.out.printf("%-10d Exception %s %n", index, e);
                        e.printStackTrace();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        countDownLatch.await(5, TimeUnit.SECONDS);
        producer.shutdown();
    }
}
